import 'package:flutter/material.dart';
import '../common/touch_callback.dart';
import '../common/wechat_item.dart';
import 'package:path_provider/path_provider.dart';
import 'dart:io';
import 'package:fluttertoast/fluttertoast.dart';
import 'package:qr_flutter/qr_flutter.dart';
import 'package:image_picker/image_picker.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'package:event_bus/event_bus.dart';
import 'package:wechatTest/custom_notification.dart';

class Personal extends StatefulWidget {
  @override
  _PersonalState createState() => _PersonalState();
}
class _PersonalState extends State<Personal> {
  String walletTitle = '钱包';
  String imageUrl = 'https://img1.baidu.com/it/u=1939348538,4074903824&fm=253&fmt=auto&app=120&f=JPEG?w=500&h=752';
  String cacheSize = '0.00KB';
  final ImagePicker _picker = ImagePicker();
  File? _imageFile;
  String selectedText = '图图测试一波';
  @override
  void initState() {
    super.initState();
    _calculateCacheSize();
    eventBus.on<TextSelectedEvent>().listen((event) {
      setState(() {
        selectedText = event.selectedText;
      });
    });
  }
  Future<void> _refresh() async {
    await Future.delayed(Duration(seconds: 1)); // 模拟网络请求延迟
    setState(() {
      walletTitle = '钱包文本发生变化';
      imageUrl = 'https://p0.itc.cn/images01/20230830/2cfbe9a4ad3b449b967d53528720c158.jpeg?timestamp=${DateTime.now().millisecondsSinceEpoch}';
    });
  }
  Future<void> _calculateCacheSize() async {
    final directory = await getTemporaryDirectory();
    final size = await _getTotalSizeOfFilesInDir(directory);
    setState(() {
      cacheSize = _formatSize(size);
    });
  }
  Future<int> _getTotalSizeOfFilesInDir(final Directory directory) async {
    final List<FileSystemEntity> children = directory.listSync();
    int totalSize = 0;
    for (final FileSystemEntity child in children) {
      if (child is File) {
        totalSize += await child.length();
      } else if (child is Directory) {
        totalSize += await _getTotalSizeOfFilesInDir(child);
      }
    }
    return totalSize;
  }
  String _formatSize(int bytes) {
    if (bytes <= 0) return '0.00KB';
    final kb = bytes / 1024;
    if (kb < 1024) {
      return '${kb.toStringAsFixed(2)}KB';
    } else {
      final mb = kb / 1024;
      return '${mb.toStringAsFixed(2)}MB';
    }
  }
  Future<void> _clearCache() async {
    final directory = await getTemporaryDirectory();
    try {
      if (directory.existsSync()) {
        directory.deleteSync(recursive: true);
      }
    } catch (e) {
      print("Error deleting cache directory: $e");
    }
    // 重新创建缓存目录
    await directory.create();
    await _calculateCacheSize();
    // 清除 SharedPreferences 中的数据
    final prefs = await SharedPreferences.getInstance();
    await prefs.clear();
    setState(() {}); // Ensure the UI is updated after clearing cache
    Fluttertoast.showToast(
      msg: "清理成功",
      toastLength: Toast.LENGTH_SHORT,
      gravity: ToastGravity.CENTER,
      timeInSecForIosWeb: 1,
      backgroundColor: Colors.black,
      textColor: Colors.white,
      fontSize: 16.0,
    );
  }
  void _showClearCacheDialog() {
    showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Center(child: Text("您确定清理缓存吗？")),
          actions: <Widget>[
            Row(
              mainAxisAlignment: MainAxisAlignment.spaceEvenly,
              children: <Widget>[
                TextButton(
                  child: Text("取消"),
                  onPressed: () {
                    Navigator.of(context).pop();
                  },
                ),
                TextButton(
                  child: Text("确定"),
                  onPressed: () async {
                    Navigator.of(context).pop();
                    await _clearCache();
                  },
                ),
              ],
            ),
          ],
        );
      },
    );
  }
  Future<void> _pickImage(ImageSource source) async {
    final pickedFile = await _picker.pickImage(source: source);
    if (pickedFile != null) {
      setState(() {
        _imageFile = File(pickedFile.path);
      });
    }
  }
  void _showImagePickerDialog() {
    showModalBottomSheet(
      context: context,
      builder: (BuildContext context) {
        return Container(
          height: 200, // 增加高度以避免溢出
          child: SingleChildScrollView( // 使用 SingleChildScrollView 包裹 Column
            child: Column(
              mainAxisSize: MainAxisSize.min, // 确保 Column 的高度适应其内容
              children: <Widget>[
                ListTile(
                  leading: Icon(Icons.camera_alt),
                  title: Text('相机'),
                  onTap: () {
                    Navigator.of(context).pop();
                    _pickImage(ImageSource.camera);
                  },
                ),
                ListTile(
                  leading: Icon(Icons.photo_library),
                  title: Text('相册'),
                  onTap: () {
                    Navigator.of(context).pop();
                    _pickImage(ImageSource.gallery);
                  },
                ),
                ListTile(
                  leading: Icon(Icons.cancel),
                  title: Text('取消'),
                  onTap: () {
                    Navigator.of(context).pop();
                  },
                ),
              ],
            ),
          ),
        );
      },
    );
  }
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RefreshIndicator(
        onRefresh: _refresh,
        child: ListView(
          children: <Widget>[
            Container(
              margin: const EdgeInsets.only(top: 20.0),
              color: Colors.white,
              height: 80.0,
              child: TouchCallBack(
                onPressed: _showImagePickerDialog,
                child: Row(
                  crossAxisAlignment: CrossAxisAlignment.center,
                  children: <Widget>[
                    Container(
                      margin: const EdgeInsets.only(left: 12.0, right: 15.0),
                      child: _imageFile == null
                          ? Image.network(
                        imageUrl,
                        width: 70.0,
                        height: 70.0,
                      )
                          : Image.file(
                        _imageFile!,
                        width: 70.0,
                        height: 70.0,
                      ),
                    ),
                    Expanded(
                      child: Column(
                        mainAxisAlignment: MainAxisAlignment.center,
                        crossAxisAlignment: CrossAxisAlignment.start,
                        children: <Widget>[
                          Text(
                            selectedText,
                            style: TextStyle(
                              fontSize: 18.0,
                              color: Color(0xFF353535),
                            ),
                          ),
                          Text(
                            '微信号 tutu',
                            style: TextStyle(
                              fontSize: 14.0,
                              color: Color(0xFFa9a9a9),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      margin: const EdgeInsets.only(left: 12.0, right: 15.0),
                      child: generateQrCode("苍井空"),
                    ),
                  ],
                ),
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: 20.0),
              color: Colors.white,
              child: WechatItem(title: walletTitle, imagePath: 'images/icon_me_money.png'),
            ),
            Container(
              margin: const EdgeInsets.only(top: 20.0),
              color: Colors.white,
              child: Column(
                children: <Widget>[
                  WechatItem(imagePath: 'images/icon_me_collect.png', title: '收藏'),
                  Padding(
                    padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                    child: Divider(
                      height: 0.5,
                      color: Color(0xFFd9d9d9),
                    ),
                  ),
                  WechatItem(imagePath: 'images/icon_me_photo.png', title: '相册'),
                  Padding(
                    padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                    child: Divider(
                      height: 0.5,
                      color: Color(0xFFd9d9d9),
                    ),
                  ),
                  WechatItem(imagePath: 'images/icon_me_card.png', title: '卡包'),
                  Padding(
                    padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                    child: Divider(
                      height: 0.5,
                      color: Color(0xFFd9d9d9),
                    ),
                  ),
                  WechatItem(imagePath: 'images/icon_me_smile.png', title: '表情'),
                  Padding(
                    padding: const EdgeInsets.only(left: 15.0, right: 15.0),
                    child: Divider(
                      height: 0.5,
                      color: Color(0xFFd9d9d9),
                    ),
                  ),
                  WechatItem(
                    imagePath: 'images/icon_me_smile.png',
                    title: '清理缓存',
                    trailingText: cacheSize,
                    onTap: _showClearCacheDialog,
                  ),
                ],
              ),
            ),
            Container(
              margin: const EdgeInsets.only(top: 20.0),
              color: Colors.white,
              child: WechatItem(
                title: '设置',
                imagePath: 'images/icon_me_setting.png',
                onTap: () {
                  Navigator.pushNamed(context, 'settingDetail');
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}
// 生成二维码的函数
Widget generateQrCode(String data, {double size = 70.0}) {
  return QrImageView(
    data: data,
    version: QrVersions.auto,
    size: size,
  );
}